package com.example.walkera.rtsp_android_client.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.walkera.rtsp_android_client.R;
import com.example.walkera.rtsp_android_client.function.ActivityCollector;
import com.example.walkera.rtsp_android_client.global.GlobalInfo;
import com.example.walkera.rtsp_android_client.function.WifiCheck;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by kaifa@lihaiping1603@aliyun.com on 2016/12/29.
 */
public class LHPWifiConnectActivity extends Activity {
    private final static String TAG="LHPWifiConnectActivity";

    private ListView mWifiListView;
    private List<ScanResult> mScanResultList;
    private WifiCheck mWifiCheck;
    private LHPWifiListAdapter mWifiListAdapter=null;
    private int reconnectTime;
    private ScanResult currentChooseWifi;
    private int mCurConNetkId=-1;
    public static final int CONNECT_WIFI_SUCCESS = 0;
    public static final int CONNECT_WIFI_FAIL = 1;
    public static final int REFRESH_TIME_OUT = 4;
    private ProgressDialog progressDialog;
    private MyHandler myHandler;
    private Timer timer;
    public static final String WIFI_AUTH_OPEN = "";
    public static final String WIFI_AUTH_ROAM = "[ESS]";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wifi_connect_lhp);

        //存储当前的activity
        GlobalInfo.getInstance().setCurrentApp(this);

        mWifiCheck = new WifiCheck();
        myHandler = new MyHandler();

        mWifiListView = (ListView) findViewById(R.id.choose_wifi_list_scan);

        mWifiListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                connectWifi();
            }
        });
        //设置为单选模式
        mWifiListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

        ActivityCollector.addActivity(this);
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        unregisterReceiver(mReceiver);
        ActivityCollector.removeActivity(this);
    }

    @Override
    protected void onPause(){
        super.onPause();
//        unregisterReceiver(mReceiver);
    }

    @Override
    protected void onResume(){
        super.onResume();
        //注册一个广播用于接受wifi扫描的通知
        final IntentFilter filter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        registerReceiver(mReceiver, filter);
        //因为wifi扫描的过程是通过启动线程来进行的，所以不确定结果出来的时间，所以这里最好通过广播来进行更新
        mWifiCheck.startScan();
        //显示进度条
        showProgressDialog(this.getString(R.string.wifi_scanning));
    }

    //接受wifi扫描结果的广播消息通知
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                if (progressDialog != null) {
                    progressDialog.dismiss();
                }
//                mScanResultList = mWifiCheck.wifiListSortWithSignalLevel(mWifiCheck.getWifiList());
                mScanResultList=mWifiCheck.getWifiListWithFilter();
                String tempSSID="null";
                String strWifiSSID=mWifiCheck.getSSID();
//                Log.d(TAG, "onReceive: ssid:"+strWifiSSID);
                if (strWifiSSID.startsWith("\"")&&strWifiSSID.endsWith("\"")){
                    tempSSID=strWifiSSID.substring(strWifiSSID.indexOf("\"")+1,strWifiSSID.lastIndexOf("\""));
                }

                if (mWifiCheck.isWifiConnected(LHPWifiConnectActivity.this,tempSSID)!=true){//如果链接了,这个时候获取的才准确，否则不正确
                    tempSSID="null";
                }
                Log.d(TAG, "onReceive: tempConnectSSID:"+tempSSID);
                //if(mWifiListAdapter==null){
                    mWifiListAdapter = new LHPWifiListAdapter(LHPWifiConnectActivity.this, mScanResultList,tempSSID);
                    mWifiListView.setAdapter(mWifiListAdapter);
//                }
            }

        }
    };
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_2://return，返回
                finish();
                break;
            case KeyEvent.KEYCODE_1://搜索
                //refreshWifiList();
                //改为启动飞机型号选择页面
                Intent intent=new Intent(LHPWifiConnectActivity.this,AirplaneChoose.class);
                startActivity(intent);
                break;
            case KeyEvent.KEYCODE_6://进行连接
                connectWifi();
                break;
            case KeyEvent.KEYCODE_7://down
                mWifiListAdapter.nextItemSelected();
//                if(mWifiListAdapter.shouldScroll())
                    mWifiListView.smoothScrollToPosition(mWifiListAdapter.getCurrentSelectedIndex());
//                    mWifiListView.smoothScrollByOffset(1);
                break;
            case KeyEvent.KEYCODE_3://up
                mWifiListAdapter.preItemSelected();
//                if(mWifiListAdapter.shouldScroll())
                    mWifiListView.smoothScrollToPosition(mWifiListAdapter.getCurrentSelectedIndex());
//                    mWifiListView.smoothScrollByOffset(-1);
                break;
            default:
                return super.onKeyDown(keyCode, event);
        }

        return true;
    }


    public void refreshWifiList(){
        if (progressDialog != null) {
                progressDialog.dismiss();
        }
        showProgressDialog(LHPWifiConnectActivity.this.getString(R.string.dialog_refreshing));
        timer = new Timer(true);
        TimerTask refreshTask = new TimerTask() {
                @Override
                public void run() {
//                    WriteLogToDevice.writeLog("[Normal] -- WifiConnectActivity: ", "appstart run:");
                    Log.d(TAG, "run: WifiConnectActivity refresh wifi list");
                    myHandler.obtainMessage(REFRESH_TIME_OUT).sendToTarget();

                }
            };
        timer.schedule(refreshTask, 5000);
    }

    public void connectWifi(){
        showProgressDialog(LHPWifiConnectActivity.this.getString(R.string.dialog_init_network));
        currentChooseWifi= mWifiListAdapter.getCurrentItemScanResult();
//        if(currentChooseWifi.capabilities==null){
//            Log.d(TAG, "connectWifi: "+currentChooseWifi.SSID+" failed,the capabilities is null");
//        }
//
//        String capabilities=currentChooseWifi.capabilities.trim();
//        if (capabilities!=null&&(capabilities.equals(WIFI_AUTH_OPEN) || capabilities.equals(WIFI_AUTH_ROAM))){
//            mCurConNetkId=mWifiCheck.connectWifi(currentChooseWifi.SSID, "", mWifiCheck.getSecurity(currentChooseWifi));
//        }
//        else {
//            mCurConNetkId=mWifiCheck.connectWifi(currentChooseWifi.SSID, "1234567890", mWifiCheck.getSecurity(currentChooseWifi));
//        }
        mCurConNetkId=mWifiCheck.connectWifi(currentChooseWifi.SSID, "1234567890", mWifiCheck.getSecurity(currentChooseWifi));
        if (mCurConNetkId==-1) {
            Log.d(TAG, "connectWifi: "+currentChooseWifi.SSID+" failed,return networkId:-1");
            return;
        }
        reconnectTime = 0;
        final Timer connectTimer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {

                if (mWifiCheck.isWifiConnected(LHPWifiConnectActivity.this, currentChooseWifi.SSID) == true) {
//                    WriteLogToDevice.writeLog("[Normal] -- WifiConnectActivity: ", "isWifiConnect() == true");
                    Log.d(TAG, "run: isWifiConnect() == true");
                    if (connectTimer != null) {
                        connectTimer.cancel();
                    }
                    myHandler.obtainMessage(CONNECT_WIFI_SUCCESS).sendToTarget();
                    return;
                } else {
//                    WriteLogToDevice.writeLog("[Normal] -- WifiConnectActivity: ", "isWifiConnect() == false  reconnectTime =" + reconnectTime);
                    Log.d(TAG, "run: isWifiConnect() == false  reconnectTime ="+reconnectTime);
                    reconnectTime++;
                    if (reconnectTime >= 20) {
                        if (connectTimer != null) {
                            connectTimer.cancel();
                        }
                        myHandler.obtainMessage(CONNECT_WIFI_FAIL).sendToTarget();
                        return;
                    }
                }
            }
        };
        connectTimer.schedule(task, 0, 3000);
    }

    private class MyHandler extends Handler {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CONNECT_WIFI_SUCCESS:
//                    WriteLogToDevice.writeLog("[Normal] -- WifiConnectActivity: ", "CONNECT_SUCCESS");
                    Log.d(TAG, "handleMessage: Wifi CONNECT_SUCCESS");
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }
                    showProgressDialog(LHPWifiConnectActivity.this.getString(R.string.dialog_connecting_to_cam));
                    //启动主页面
                    Intent intent = new Intent(LHPWifiConnectActivity.this, MainActivity.class);
                    startActivity(intent);
                    break;
                case CONNECT_WIFI_FAIL:
//                    WriteLogToDevice.writeLog("[Normal] -- WifiConnectActivity: ", "CONNECT_FAIL");
                    Log.d(TAG, "handleMessage: wifi CONNECT_FAIL");
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }
                    if (mCurConNetkId!=-1){
                        mWifiCheck.disconnectWifi(mCurConNetkId);
                    }
                    Toast.makeText(LHPWifiConnectActivity.this, R.string.dialog_connect_failed, Toast.LENGTH_LONG).show();
                    break;
                case REFRESH_TIME_OUT:
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }
                    mWifiListAdapter.notifyDataSetChanged();
//                    mScanResultList = mWifiCheck.wifiListSortWithSignalLevel(mWifiCheck.getWifiList());
                    mScanResultList=mWifiCheck.getWifiListWithFilter();
                    mWifiListAdapter = new LHPWifiListAdapter(LHPWifiConnectActivity.this, mScanResultList,mWifiCheck.getSSID());
                    mWifiListView.setAdapter(mWifiListAdapter);
                    break;
            }

        }
    }

    private void showProgressDialog(String message) {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        progressDialog = new ProgressDialog(LHPWifiConnectActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage(message);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }


    //暂时屏蔽这个函数，防止弹出以后，无法用按键操作的后果，主要用于鼠标操作的时候，进行调试
    private void showDialog(String message) {
//        AlertDialog.Builder builder = new AlertDialog.Builder(LHPWifiConnectActivity.this);
//        builder.setMessage(message);
//        builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
//
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                dialog.dismiss();
//            }
//        });
//        AlertDialog dialog = builder.create();
//        dialog.setCancelable(false);
//        dialog.show();
    }


}
